package com.lixinlei.mc.api.service;

import gnu.io.CommPortIdentifier;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Enumeration;

public class WindowsComPortList {

    private static final Logger LOGGER = LoggerFactory.getLogger(WindowsComPortList.class);

    public String listPort() {
        String res = null;
        try {
            Enumeration<?> ports = CommPortIdentifier.getPortIdentifiers();
            CommPortIdentifier port = null;
            String type = null;
            System.out.println("COM端口列表：");
            while (ports.hasMoreElements()) {
                port = (CommPortIdentifier) ports.nextElement();
                switch (port.getPortType()) {
                    case CommPortIdentifier.PORT_PARALLEL:
                        type = "Parallel";
                        break;
                    case CommPortIdentifier.PORT_SERIAL:
                        type = "Serial";
                        break;
                    default: // / Shouldn't happen
                        type = "Unknown";
                        break;
                }
                if (StringUtils.isBlank(res)) {
                    res = port.getName() + ":" + type + " 是否占用-" + port.isCurrentlyOwned();
                } else {
                    res = res + ";" + port.getName() + ":" + type + " 是否占用-" + port.isCurrentlyOwned();
                }
//                System.out.println("   " + port.getName() + ":" + type + " 是否占用-" + port.isCurrentlyOwned());
            }
        } catch (Exception e) {
            LOGGER.error("查询端口列表错误：" + e.getMessage());
        }

        return res;
    }

    public static void main(String[] args) {
        String ports = new WindowsComPortList().listPort();
        System.out.println(ports);
    }

}
